import type { App } from 'vue'

export const clickOutside = (app: App<Element>) => {
  app.directive('clickOutSide', {
    beforeMount(el, binding) {
      el.clickOutsideEvent = (event) => {
        if (!(el === event.target || el.contains(event.target))) {
          if (typeof binding.value === 'function') {
            binding.value()
          }
        }
      }
      document.addEventListener('click', el.clickOutsideEvent)
    },
    unmounted(el) {
      document.removeEventListener('click', el.clickOutsideEvent)
    }
  })
}
